# 创建推荐系统管理页面
<template>
  <div class="recommendation-container">
    <!-- 基础推荐功能卡片 -->
    <el-card class="recommendation-card">
      <template #header>
        <div class="card-header">
          <span>基础推荐功能测试</span>
        </div>
      </template>
      
      <el-form :inline="true" class="recommendation-form">
        <el-form-item label="用户ID">
          <el-input v-model="userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="商品ID" v-if="showProductId">
          <el-input v-model="productId" placeholder="请输入商品ID" clearable />
        </el-form-item>
        <el-form-item label="返回数量">
          <el-input-number v-model="limit" :min="1" :max="100" />
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="getPersonalized">个性化推荐</el-button>
            <el-button type="primary" @click="getSimilar">相似商品</el-button>
            <el-button type="primary" @click="getHot">热门商品</el-button>
            <el-button type="primary" @click="getNew">新品推荐</el-button>
            <el-button type="primary" @click="getBrowseHistory">浏览推荐</el-button>
            <el-button type="primary" @click="getFavorite">收藏推荐</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>

      <!-- 推荐结果表格 -->
      <el-table v-loading="loading" :data="recommendProducts" style="width: 100%">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column label="主图" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.mainImage"
              :src="row.mainImage"
              :preview-src-list="[row.mainImage]"
              fit="cover"
              class="product-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ formatPrice(row.price) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="推荐分数" width="100" sortable />
      </el-table>
    </el-card>

    <!-- 实验组管理卡片 -->
    <el-card class="experiment-card">
      <template #header>
        <div class="card-header">
          <span>实验组管理</span>
          <el-button-group>
            <el-button type="primary" @click="refreshExperiments">刷新实验配置</el-button>
            <el-button type="primary" @click="showMetricsDialog">查看效果指标</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 实验组用户管理 -->
      <el-form :inline="true" class="experiment-form">
        <el-form-item label="用户ID">
          <el-input v-model="experimentUserId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="queryExperimentGroup">查询实验组</el-button>
            <el-button type="warning" @click="reassignExperimentGroup">重新分配</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>

      <!-- 实验组信息表格 -->
      <el-table v-loading="experimentLoading" :data="experimentGroups" style="width: 100%">
        <el-table-column prop="groupName" label="实验组" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userCount" label="用户数" width="100" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '活跃' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="showGroupUsers(row)">查看用户</el-button>
              <el-button type="warning" link @click="showReassignDialog(row)">批量分配</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 效果指标对话框 -->
    <el-dialog
      v-model="metricsDialogVisible"
      title="实验组效果指标"
      width="80%"
    >
      <el-form :inline="true" class="metrics-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="metricsDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchMetrics">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="metricsLoading" :data="metricsData" style="width: 100%">
        <el-table-column prop="groupName" label="实验组" width="150" />
        <el-table-column prop="impressions" label="展现量" width="120" sortable />
        <el-table-column prop="clicks" label="点击量" width="120" sortable />
        <el-table-column prop="ctr" label="点击率" width="120" sortable>
          <template #default="{ row }">
            {{ (row.ctr * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="conversions" label="转化量" width="120" sortable />
        <el-table-column prop="cvr" label="转化率" width="120" sortable>
          <template #default="{ row }">
            {{ (row.cvr * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column prop="gmv" label="GMV" min-width="150" sortable>
          <template #default="{ row }">
            ¥{{ formatPrice(row.gmv) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 批量分配对话框 -->
    <el-dialog
      v-model="reassignDialogVisible"
      title="批量分配实验组"
      width="500px"
    >
      <el-form :model="reassignForm" label-width="100px">
        <el-form-item label="目标实验组">
          <el-select v-model="reassignForm.targetGroup" placeholder="请选择实验组">
            <el-option
              v-for="group in experimentGroups"
              :key="group.groupName"
              :label="group.groupName"
              :value="group.groupName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID列表">
          <el-input
            v-model="reassignForm.userIds"
            type="textarea"
            :rows="4"
            placeholder="请输入用户ID，多个ID用逗号分隔"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reassignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReassign">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getPersonalizedRecommendations,
  getSimilarProducts,
  getHotProducts,
  getNewProducts,
  getBrowseHistoryRecommendations,
  getFavoriteRecommendations,
  queryUserExperimentGroups,
  reassignUserExperimentGroup,
  reassignUsersToGroup,
  getActiveExperiments,
  getExperimentGroupUserCounts,
  getExperimentGroupMetrics,
  getUserRecommendationHistory
} from '@/api/statistics'

// 基础推荐功能相关
const loading = ref(false)
const userId = ref('')
const productId = ref('')
const limit = ref(20)
const showProductId = ref(false)
const recommendProducts = ref([])

// 实验组管理相关
const experimentLoading = ref(false)
const experimentUserId = ref('')
const experimentGroups = ref([])
const reassignDialogVisible = ref(false)
const reassignForm = ref({
  targetGroup: '',
  userIds: ''
})

// 效果指标相关
const metricsDialogVisible = ref(false)
const metricsLoading = ref(false)
const metricsDateRange = ref([])
const metricsData = ref([])

// 基础推荐功能方法
const getPersonalized = async () => {
  if (!userId.value) {
    ElMessage.warning('请输入用户ID')
    return
  }
  showProductId.value = false
  try {
    loading.value = true
    const res = await getPersonalizedRecommendations(userId.value, limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取个性化推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

const getSimilar = async () => {
  if (!productId.value) {
    ElMessage.warning('请输入商品ID')
    return
  }
  showProductId.value = true
  try {
    loading.value = true
    const res = await getSimilarProducts(productId.value, limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取相似商品推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

const getHot = async () => {
  showProductId.value = false
  try {
    loading.value = true
    const res = await getHotProducts(limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取热门商品推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

const getNew = async () => {
  showProductId.value = false
  try {
    loading.value = true
    const res = await getNewProducts(limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取新品推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

const getBrowseHistory = async () => {
  if (!userId.value) {
    ElMessage.warning('请输入用户ID')
    return
  }
  showProductId.value = false
  try {
    loading.value = true
    const res = await getBrowseHistoryRecommendations(userId.value, limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取浏览历史推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

const getFavorite = async () => {
  if (!userId.value) {
    ElMessage.warning('请输入用户ID')
    return
  }
  showProductId.value = false
  try {
    loading.value = true
    const res = await getFavoriteRecommendations(userId.value, limit.value)
    if (res.code === 200) {
      recommendProducts.value = res.data
    }
  } catch (error) {
    console.error('获取收藏推荐失败:', error)
    ElMessage.error('获取推荐失败')
  } finally {
    loading.value = false
  }
}

// 实验组管理方法
const refreshExperiments = async () => {
  try {
    experimentLoading.value = true
    const [experimentsRes, countsRes] = await Promise.all([
      getActiveExperiments(),
      getExperimentGroupUserCounts()
    ])
    
    if (experimentsRes.code === 200 && countsRes.code === 200) {
      experimentGroups.value = experimentsRes.data.map(exp => ({
        ...exp,
        userCount: countsRes.data[exp.groupName] || 0
      }))
    }
  } catch (error) {
    console.error('刷新实验配置失败:', error)
    ElMessage.error('刷新失败')
  } finally {
    experimentLoading.value = false
  }
}

const queryExperimentGroup = async () => {
  if (!experimentUserId.value) {
    ElMessage.warning('请输入用户ID')
    return
  }
  
  try {
    experimentLoading.value = true
    const res = await queryUserExperimentGroups([experimentUserId.value])
    if (res.code === 200) {
      const groupInfo = res.data[experimentUserId.value]
      if (groupInfo) {
        ElMessage.success(`用户所在实验组: ${groupInfo.groupName}`)
      } else {
        ElMessage.warning('未找到用户实验组信息')
      }
    }
  } catch (error) {
    console.error('查询实验组失败:', error)
    ElMessage.error('查询失败')
  } finally {
    experimentLoading.value = false
  }
}

const reassignExperimentGroup = async () => {
  if (!experimentUserId.value) {
    ElMessage.warning('请输入用户ID')
    return
  }
  
  try {
    experimentLoading.value = true
    const res = await reassignUserExperimentGroup(experimentUserId.value)
    if (res.code === 200) {
      ElMessage.success(`重新分配成功，当前实验组: ${res.data.groupName}`)
      await refreshExperiments()
    }
  } catch (error) {
    console.error('重新分配实验组失败:', error)
    ElMessage.error('分配失败')
  } finally {
    experimentLoading.value = false
  }
}

const showReassignDialog = (group) => {
  reassignForm.value = {
    targetGroup: group.groupName,
    userIds: ''
  }
  reassignDialogVisible.value = true
}

const submitReassign = async () => {
  if (!reassignForm.value.targetGroup || !reassignForm.value.userIds) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  try {
    const userIds = reassignForm.value.userIds.split(',').map(id => id.trim())
    const res = await reassignUsersToGroup(userIds, reassignForm.value.targetGroup)
    if (res.code === 200) {
      ElMessage.success(`成功分配 ${res.data} 个用户`)
      reassignDialogVisible.value = false
      await refreshExperiments()
    }
  } catch (error) {
    console.error('批量分配失败:', error)
    ElMessage.error('分配失败')
  }
}

// 效果指标相关方法
const showMetricsDialog = () => {
  const now = new Date()
  const sevenDaysAgo = new Date(now - 7 * 24 * 60 * 60 * 1000)
  metricsDateRange.value = [
    sevenDaysAgo.toISOString().slice(0, 19).replace('T', ' '),
    now.toISOString().slice(0, 19).replace('T', ' ')
  ]
  metricsDialogVisible.value = true
  fetchMetrics()
}

const fetchMetrics = async () => {
  if (!metricsDateRange.value || metricsDateRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }
  
  try {
    metricsLoading.value = true
    const res = await getExperimentGroupMetrics(
      metricsDateRange.value[0],
      metricsDateRange.value[1]
    )
    if (res.code === 200) {
      metricsData.value = Object.entries(res.data).map(([groupName, metrics]) => ({
        groupName,
        ...metrics
      }))
    }
  } catch (error) {
    console.error('获取效果指标失败:', error)
    ElMessage.error('获取指标失败')
  } finally {
    metricsLoading.value = false
  }
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

onMounted(() => {
  refreshExperiments()
})
</script>

<style scoped>
.recommendation-container {
  padding: 20px;
}

.recommendation-card,
.experiment-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendation-form,
.experiment-form,
.metrics-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.price {
  color: var(--el-color-danger);
  font-weight: bold;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

.metrics-form {
  margin-bottom: 20px;
}
</style>